import Vue from 'vue'
import Request from '@/common/luch-request/index.js'
import configService from './config.service.js'
import Tips from '@/common/util/Tips.js';
Vue.use(Tips)
// import codeError from '../data/errcode.js';
import store from '@/store/index.js';
Vue.use(store)

let apiUrl = configService.apiUrl;

const getTokenStorage = () => {
	let token = ''
	try {
		token = store.state.token
		console.debug('token', token);
	} catch (e) {
		//TODO handle the exception
		console.debug("getTokenStorage", token)
	}
	return token || ''
}

const http = new Request()
http.setConfig((config) => {
	/* 设置全局配置 */
	config.baseURL = apiUrl /* 根域名不同 */
	config.header = {
		...config.header
	}
	config.custom = {
		auth: true, // 是否传token
		loading: false // 是否使用loading
	}
	return config
})

http.interceptors.request.use((config) => {
	/* 请求之前拦截器。可以使用async await 做异步操作 */
	config.header = {
		...config.header
	}
	/**
	 * custom {Object} - 自定义参数
	 */
	if (config.custom.auth) {
		config.header.token = getTokenStorage()

	}
	if (config.custom.loading) {
		uni.showLoading()
	}
	console.debug(config);
	// config.isConnected = store.state.networkType && store.state.networkType != 'none'
	// if (!config.isConnected) {
	// 	return Promise.reject(config)
	// }
	//没有uid直接不发起请求
	// if(config.url === '/user/info' && !config.header.uid){
	// 	return Promise.reject(config)
	// }

	return config
}, (config) => {
	return Promise.reject(config)
})

// 必须使用异步函数，注意
http.interceptors.response.use(async (response) => {
	/* 请求之后拦截器。可以使用async await 做异步操作  */

	// console.debug('response',response);
	if (response.config.custom.loading) {
		uni.hideLoading()
	}

	// response.isConnected = response.config.isConnected

	const {
		data: {
			token
		}
	} = response
	token && store.dispatch('set_token', token)
	if (response.data.code !== 0) { // 服务端返回的状态码不等于0，则reject()
		response.data.code === undefined && console.debug("没有code或者 undefined ", response);
		// codeError(response.data.code)
		return Promise.reject(response)
	}
	// 设置服务器错误状态
	Vue.prototype.$store.state.serverError = response.serverError = (!response.statusCode || response
		.statusCode != 200)
	return response
}, (response) => {
	// 设置服务器错误状态
	if (response.url != '/user/info') {
		Vue.prototype.$store.state.serverError = response.serverError = true;
	}
	if (!response.statusCode) return Promise.reject(Object.assign(
		response, { error: 'uid or token is null' }));
	// 请求错误做点什么
	console.debug("请求错误做点什么", response);
	if (response.config.custom.loading) {
		uni.hideLoading()
	}
	return Promise.reject(response)
})

export default http
